from rqalpha.api import *
from rqalpha.utils.logger import user_log, system_log
import numpy as np

'''
ma5>ma20 做多，否则做空
测试用例：讯投文件单测试策略，限价单
'''

static_param = {"future_vol": 1, "stock_amount": 100000,"stock_shares":200,"stock_lots":1, "stock_percent": 0.04,"stock_transaction":0.0008}
dynamic_param = {"main_contract": None,"last_main_contract": None, "is_switch": False}


def init(context):
    """
    context内引入全局变量s1，存储目标合约信息
    :param context: 策略上下文
    :return:
    """
    user_log.info("init")
    context.stock_symbol = '000625.SZ'
    subscribe(context.stock_symbol)


def before_trading(context):
    pass


def handle_bar(context, bar_dict):
    """
    :param context: 策略上下文
    :param bar_dict: 当前合约池内所有合约的bar数据信息都会更新在bar_dict里面
    :return:
    """
    bar = bar_dict[context.stock_symbol]
    bar_datetime = bar_dict.dt
    close: np.ndarray = history_bars(context.stock_symbol, 20, "1m", ['close'],adjust_type = "none")
    if len(close) < 20:
        return
    if close[-5:].mean() > close.mean():
        buy_stock(context,bar_dict[context.stock_symbol].close)
    else:
        sell_stock(context,bar_dict[context.stock_symbol].close)


def buy_stock(context, cur_price):
    """
    买入股票：buy_stock(context)
    :param context: 策略上下文
    :param cur_price: 当前价格
    :return:
    """
    qty = context.portfolio.positions[context.stock_symbol].quantity
    if qty <= 0:
        buy_order_2 = order_shares(context.stock_symbol, static_param["stock_shares"], price=cur_price)
        user_log.info("指定股数开仓={}".format(buy_order_2))


def sell_stock(context, cur_price):
    """
    卖出股票：sell_stock(context)
    :param context: 策略上下文
    :param cur_price: 当前价格
    :return:
    """
    qty = context.portfolio.positions[context.stock_symbol].sellable
    if qty > 0:
        sell_order_2 = order_lots(context.stock_symbol, -static_param["stock_lots"], price=cur_price)
        user_log.info("指定手数平仓={}".format(sell_order_2))
